import axios from 'axios'
import { ElMessage } from "element-plus";
import {useCounterStore} from '@/stores/counter'


// 请求拦截器
axios.interceptors.request.use(
  (config) => {
    const counter = useCounterStore();
    const token=counter.userinfo.token
    console.log(counter.userinfo.token)
     //const token=window.localStorage.getItem("token")
    if (token) {
      config.headers["Authorization"] = `Bearer${token}`;
      //config.headers.Authorization = localStorage.token;  //将token设置成请求头
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
axios.interceptors.response.use(
  (response) => {
    //如果失败 弹出错误信息
    if (!response.data.isSuc) {
      ElMessage.error(response.data.msg);
      return Promise.reject(new Error(response.data.msg));
    }
    return response.data;
  },
  (error) => {
    const { response, message } = error;
    if (response) {
      switch (response.status) {
        case 401:
          sessionStorage.removeItem("token");
          ElMessage.error("请先登录");
          window.location.href = "/"; // 跳转到登录页面
          break;
        default:
          console.error(`请求错误：${response.status}`);
          ElMessage.error(`请求错误：${response.status}`);
      }
    } else {
      ElMessage.error("网络连接异常" + message);
    }
    return Promise.reject(error);
  }
);
  
//导出axios实例
export default axios;
  


